package com.touka.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody // 该类的方法返回值会被封装成json格式数据返回
@Slf4j
public class GlobalExceptionHandler {
  /**
   * 异常处理方法
   *
   * @return
   */
  @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
  public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
    log.error(exception.getMessage());
    if (exception.getMessage().contains("Duplicate entry")) {
      String[] split = exception.getMessage().split(" ");
      return Result.error(split[2] + "已存在");
    }
    return Result.error("失败了");
  }

  /**
   * 异常处理方法
   *
   * @return
   */
  @ExceptionHandler(CustomException.class)
  public Result<String> exceptionHandler(CustomException exception) {
    log.error(exception.getMessage());

    return Result.error(exception.getMessage());
  }
}
